package com.yrd.fssync.core;

import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import javax.swing.ImageIcon;

import com.yrd.common.handler.Handler;
import com.yrd.common.handler.HandlerThread;
import com.yrd.common.webui.HttpEngine;

public class Tray {
	boolean support;
	Context context;
	SystemTray systemTray;
	TrayIcon trayIcon;
	ImageIcon iconBlue = new ImageIcon("blue.png"); 
    ImageIcon iconRed = new ImageIcon("red.png"); 
    ImageIcon iconYellow = new ImageIcon("yellow.png");
    
    HandlerThread thread;
    Handler handler;
    enum Status{
    	unkown,normal,loading,uping,error
    } 
    Status status;
    
	public Tray(Context context) {
		this.context = context;
		context.setTray(this);
		support = SystemTray.isSupported();
		if(!support)return;
		
		thread = new HandlerThread("tray");
		thread.start();
		handler = new Handler(thread.getLooper());
		systemTray = SystemTray.getSystemTray();
		iconBlue = new ImageIcon(this.getClass().getClassLoader().getResource("res/blue.png")); 
	    iconRed = new ImageIcon(this.getClass().getClassLoader().getResource("res/red.png")); 
	    iconYellow = new ImageIcon(this.getClass().getClassLoader().getResource("res/yellow.png"));
		PopupMenu popupMenu = new PopupMenu(); 
        MenuItem mi = new MenuItem("打开主面板"); 
        MenuItem exit = new MenuItem("退出"); 
        popupMenu.add(mi); 
        popupMenu.add(exit); 
        trayIcon = new TrayIcon(iconYellow.getImage(), "文件同步器", popupMenu);
        trayIcon.setImageAutoSize(true);
        mi.addActionListener(new ActionListener(){ 
            public void actionPerformed(ActionEvent e) {
            	InetSocketAddress address = HttpEngine.getInstance().getAddress();
            	java.net.URI uri=java.net.URI.create("http://localhost:"+address.getPort());
                java.awt.Desktop dp=java.awt.Desktop.getDesktop();
                if(dp.isSupported(java.awt.Desktop.Action.BROWSE)){
                    try {
						dp.browse(uri);
					} catch (IOException e1) {
						e1.printStackTrace();
						info("文件同步器","打开浏览器失败");
					}
                }
            } 

        }); 
        exit.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) { 
            		new Thread(new Runnable() {
						public void run() {
							try {
								info("文件同步器", "正在关闭");
								Tray.this.context.getApp().stop();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}).start();
            } 
        }); 
	}
	
	public void start(){
		if(!support)return;
        try {
			systemTray.add(trayIcon);
			statusLoading();
		} catch (AWTException e) {
			e.printStackTrace();
		} 
	}
	public void stop(){
		if(!support)return;
		systemTray.remove(trayIcon);
		thread.quit();
	}
	public void info(String title,String message){
		if(!support)return;
        trayIcon.displayMessage(title, message, TrayIcon.MessageType.INFO);
	}
	Runnable done = new Runnable() {
		public void run() {
			trayIcon.setImage(iconYellow.getImage());
		}
	};
	Runnable upingBlue = new Runnable() {
		public void run() {
			trayIcon.setImage(iconBlue.getImage());
			handler.post(upingYellow, 1000);
		}
	};
	Runnable upingYellow = new Runnable() {
		public void run() {
			trayIcon.setImage(iconYellow.getImage());
			handler.post(upingBlue, 1000);
		}
	};
	Runnable loadingRed = new Runnable() {
		public void run() {
			trayIcon.setImage(iconRed.getImage());
			handler.post(loadingYellow, 1000);
		}
	};
	Runnable loadingYellow = new Runnable() {
		public void run() {
			trayIcon.setImage(iconYellow.getImage());
			handler.post(loadingRed, 1000);
		}
	};
	Runnable error = new Runnable() {
		public void run() {
			trayIcon.setImage(iconRed.getImage());
		}
	};
	private void statusClear(){
		if(!support)return;
		handler.remove(done);
		handler.remove(upingBlue);
		handler.remove(upingYellow);
		handler.remove(loadingRed);
		handler.remove(loadingYellow);
		handler.remove(error);
	} 
	public void statusNormal(){
		if(!support)return;
		handler.post(new Runnable() {
			public void run() {
				if(status==Status.normal)return;
				trayIcon.setToolTip("文件同步器");
				status=Status.normal;
				statusClear();
				handler.post(done);
			}
		});
	}
	public void statusUping(final String fileName){
		if(!support)return;
		handler.post(new Runnable() {
			public void run() {
				trayIcon.setToolTip(fileName);
				if(status==Status.uping)return;
				status=Status.uping;
				statusClear();
				handler.post(upingBlue);
			}
		});
	}
	public void statusLoading(){
		if(!support)return;
		handler.post(new Runnable() {
			public void run() {
				if(status==Status.loading)return;
				trayIcon.setToolTip("启动中");
				status=Status.loading;
				statusClear();
				handler.post(loadingYellow);
			}
		});
	}
	public void statusError(){
		if(!support)return;
		handler.post(new Runnable() {
			public void run() {
				if(status==Status.error)return;
				trayIcon.setToolTip("发生错误");
				status=Status.error;
				statusClear();
				handler.post(error);
			}
		});
	}
	
}
